<?php
class ProjectFundsController extends AppController
{
    public $name = 'ProjectFunds';
    public function beforeFilter()
    {
        $this->Security->disabledFields = array(
            'ProjectFund.amount',
            'ProjectFund.project_reward_id',
            'ProjectFund.latitude',
            'ProjectFund.longitude',
        );
        parent::beforeFilter();
    }
    public function data()
    {
        $conditions = array();
        $project_funds = $this->ProjectFund->find('all', array(
            'conditions' => array(
                'OR' => array(
                    array(
                        'ProjectFund.is_paid' => 1
                    ) ,
                    array(
                        'ProjectFund.is_paid' => 0
                    ) ,
                ) ,
                'Project.slug' => $this->request->params['named']['project'],
                'ProjectFund.is_cancelled' => 0,
                'ProjectFund.is_refunded' => 0
            ) ,
            'contain'=>array(
				'User'=>array(
					'UserAvatar',
				),
				'Project',
			),
            'recursive' => 1,
        ));
        $data = array();
        $i = 0;
        $user_default_image = $this->ProjectFund->Project->Attachment->find('all', array(
            'conditions' => array(
                'foreign_id' => 0,
                'class' => array(
                    'UserAvatar'
                ) ,
            ) ,
        ));
        foreach($project_funds as $project_fund) {
            if (!empty($project_fund['ProjectFund']['latitude']) && $project_fund['ProjectFund']['longitude']) {
				$image_options = array(
                    'dimension' => 'small_thumb',
                    'class' => '',
                    'alt' => $project_fund['User']['username'],
                    'title' => $project_fund['User']['username'],
                    'type' => 'jpg'
                );
               if (empty($project_fund['User']['UserAvatar'])) {
                    $project_fund['User']['UserAvatar'] = $user_default_image[0]['Attachment'];
                }
				$user_url=Router::url(array(
                    'controller' => 'users',
                    'action' => 'view',
                    $project_fund['User']['username']
                ) , true);
                $data[$i]['latitude'] = $project_fund['ProjectFund']['latitude'];
                $data[$i]['longitude'] = $project_fund['ProjectFund']['longitude'];
                $data[$i]['url'] =  '<img src="'.Router::url('/', true) . $this->ProjectFund->Project->getImageUrl('UserAvatar', $project_fund['User']['UserAvatar'], $image_options).'" /> <a href="'.$user_url.'"> '. $project_fund['User']['username'].'</a> '.__l('has backed').' '.Configure::read('site.currency').$project_fund['ProjectFund']['amount'];
                $i++;
            }
        }
        $data['Count'] = count($data);
        $this->view = 'Json';
        $this->set('json', $data);
    }
    public function reward_update($id)
    {
        $projectFund = $this->ProjectFund->find('first', array(
            'conditions' => array(
                'ProjectFund.id' => $id
            ) ,
            'contain' => array(
                'Project'
            ) ,
        ));
        if (empty($projectFund) || ($projectFund['Project']['user_id'] != $this->Auth->user('id'))) {
            throw new NotFoundException(__l('Invalid request'));
        }
        $this->ProjectFund->Behaviors->detach('Logable');
        $this->request->data['ProjectFund']['id'] = $id;
        $this->request->data['ProjectFund']['user_id'] = $projectFund['ProjectFund']['user_id'];
        $this->request->data['ProjectFund']['project_id'] = $projectFund['ProjectFund']['project_id'];
        $this->request->data['ProjectFund']['is_given'] = $projectFund['ProjectFund']['is_given'] ? '0' : '1';
        $this->request->data['ProjectFund']['reward_given_date'] = date('Y-m-d H:i:s');
        $this->ProjectFund->save($this->request->data, false);
        //$this->Session->setFlash(__l('Successfully updated') , 'default', null, 'success');
        $this->autoRender = false;
        echo $this->request->data['ProjectFund']['is_given'];
		exit;
    }
	
    public function index()
    {
        if (empty($this->request->params['named']['project_id']) && (empty($this->request->params['named']['type']) || $this->request->params['named']['type'] != 'mydonations')) {
            throw new NotFoundException(__l('Invalid request'));
        }
        $conditions = array();
        if (!empty($this->request->params['named']['type']) && $this->request->params['named']['type'] == 'mydonations' && empty($this->request->params['named']['status'])) {
            $conditions['ProjectFund.user_id'] = $this->Auth->user('id');
            $conditions['ProjectFund.is_paid <>'] = NULL;
        } else if (!empty($this->request->params['named']['type']) && $this->request->params['named']['type'] == 'mydonations' && $this->request->params['named']['status'] == 'backed') {
            $conditions['ProjectFund.user_id'] = $this->Auth->user('id');
            $conditions['Project.project_status_id'] = ConstProjectStatus::OpenForFunding;
            $conditions['ProjectFund.is_paid'] = 0;
            $conditions['ProjectFund.is_refunded'] = 0;
            $conditions['ProjectFund.is_failed'] = 0;
        } else if (!empty($this->request->params['named']['type']) && $this->request->params['named']['type'] == 'mydonations' && $this->request->params['named']['type'] == 'mydonations' && $this->request->params['named']['status'] == 'refunded') {
            $conditions['ProjectFund.user_id'] = $this->Auth->user('id');
            $conditions['ProjectFund.is_refunded'] = 1;
            $conditions['ProjectFund.is_paid <>'] = NULL;
        } else if (!empty($this->request->params['named']['type']) && $this->request->params['named']['type'] == 'mydonations' && $this->request->params['named']['status'] == 'paid') {
            $conditions['ProjectFund.user_id'] = $this->Auth->user('id');
            $conditions['Project.project_status_id <>'] = ConstProjectStatus::OpenForFunding;
            $conditions['ProjectFund.is_paid'] = 1;
        } 
		else if(!empty($this->request->params['named']['type']) && $this->request->params['named']['type'] == 'mydonations' && $this->request->params['named']['status'] == 'failed')
		{
			$conditions['ProjectFund.user_id'] = $this->Auth->user('id');
            $conditions['ProjectFund.is_failed'] = 1;
		}
		else {
            $conditions['ProjectFund.project_id'] = $this->request->params['named']['project_id'];
            $conditions['ProjectFund.is_failed'] = 0;
            $conditions['ProjectFund.is_refunded'] = 0;
            $conditions['ProjectFund.is_paid <>'] = NULL;
        }
        if (!empty($this->request->params['named']['filter'])) {
            switch ($this->request->params['named']['filter']) {
            case 'given':
                $conditions['ProjectFund.is_given'] = 1;
                break;

            case 'not_given':
				$conditions['ProjectFund.project_reward_id !='] = 0;
                $conditions['ProjectFund.is_given'] = 0;
                break;
            }
        }
        $backer = 0;
        if (!empty($this->request->params['named']['type']) && $this->request->params['named']['type'] == 'mydonations') {
            $limit = 10;
        }
        if (!empty($this->request->params['named']['project_id'])) {
            $backer = $this->ProjectFund->find('count', array(
                'conditions' => array(
                    'OR' => array(
                        array(
                            'ProjectFund.is_paid' => 1
                        ) ,
                        array(
                            'ProjectFund.is_paid' => 0
                        ) ,
                    ) ,
                    'ProjectFund.project_id' => $this->request->params['named']['project_id'],
                    'ProjectFund.user_id' => $this->Auth->user('id') ,
                    'ProjectFund.is_cancelled' => 0,
                    'ProjectFund.is_refunded' => 0,
                    'ProjectFund.is_failed' => 0
                ) ,
                'recursive' => - 1
            ));
        }
        if (!empty($this->request->params['named']['type']) && $this->request->params['named']['type'] == 'mydonations') {
            $this->set('fund_count', $this->ProjectFund->find('count', array(
                'conditions' => array(
                    'ProjectFund.user_id' => $this->Auth->user('id') ,
                    'OR' => array(
                        array(
                            'ProjectFund.is_paid' => 1
                        ) ,
                        array(
                            'ProjectFund.is_paid' => 0
                        ) ,
                    ) ,
                )
            )));
            /// Status Based on Count
            
            $this->set('backed_count', $this->ProjectFund->find('count', array(
                'conditions' => array(
                    'ProjectFund.user_id = ' => $this->Auth->user('id') ,
                    'ProjectFund.is_paid' => 0,
                    'ProjectFund.is_refunded' => 0,
                    'ProjectFund.is_cancelled' => 0,
                    'ProjectFund.is_failed' => 0,
                    'Project.project_status_id' => ConstProjectStatus::OpenForFunding
                )
            )));
            $this->set('refunded_count', $this->ProjectFund->find('count', array(
                'conditions' => array(
                    'ProjectFund.user_id = ' => $this->Auth->user('id') ,
                    'ProjectFund.is_refunded' => 1
                )
            )));
			$this->set('failed_count', $this->ProjectFund->find('count', array(
                'conditions' => array(
                    'ProjectFund.user_id = ' => $this->Auth->user('id') ,
                    'ProjectFund.is_failed' => 1
                )
            )));
            $this->set('paid_count', $this->ProjectFund->find('count', array(
                'conditions' => array(
                    'OR' => array(
                        array(
                            'ProjectFund.is_paid' => 1
                        ) ,
                        array(
                            'ProjectFund.is_paid' => 0
                        ) ,
                    ) ,
                    'ProjectFund.user_id = ' => $this->Auth->user('id') ,
                    'ProjectFund.is_paid' => 1,
                    'Project.project_status_id <>' => ConstProjectStatus::OpenForFunding
                )
            )));
        }
        $this->set('backer', $backer);
        $this->pageTitle = __l('Project Funds');
        $paging_array = array(
            'conditions' => $conditions,
            'contain' => array(
                'User' => array(
                    'UserAvatar' => array(
                        'fields' => array(
                            'UserAvatar.id',
                            'UserAvatar.dir',
                            'UserAvatar.filename',
                            'UserAvatar.width',
                            'UserAvatar.height'
                        )
                    ) ,
                    'fields' => array(
                        'User.username',
                        'User.unique_project_fund_count',
                        'User.unique_project_fund_count',
                        'User.id'
                    )
                ) ,
                'ProjectReward',
                'Project' => array(
                    'User' => array(
                        'fields' => array(
                            'User.username',
                            'User.id'
                        )
                    ) ,
                    'fields' => array(
                        'Project.id',
                        'Project.name',
                        'Project.slug',
                        'Project.user_id',
                        'Project.collected_amount',
                        'Project.needed_amount',
                        'Project.project_status_id',
                        'Project.project_funding_end_date',
                        'Project.collected_percentage',
                        'Project.project_fund_count',
                    ) ,
                    'ProjectStatus',
                )
            ) ,
            'recursive' => 2,
            'order' => array(
                'ProjectFund.id' => 'desc'
            )
           
        );
		if(!empty($limit))
        {
         $paging_array['limit'] = $limit;
        }
        $this->paginate = $paging_array;
		
		if ($this->RequestHandler->prefers('json')) {
		
			$iphone_project_backers = $this->paginate();
			$iphone_project_backer = array();
			for($i=0;$i<count($iphone_project_backers);$i++)
			{	
				$month = date('F',strtotime($iphone_project_backers[$i]['ProjectFund']['created']));
				$year = date('Y',strtotime($iphone_project_backers[$i]['ProjectFund']['created']));
				$date = date('d',strtotime($iphone_project_backers[$i]['ProjectFund']['created']));
				$created = $month." ".$date. " ".$year;
				
				$other_count = $iphone_project_backers[$i]['User']['unique_project_fund_count'] - 1;
				
				$image_options = array(
            			'dimension' => 'iphone_project_thumb',
            			'class' => '',
            			'alt' => 'alt',
            			'title' => 'title',
            			'type' => 'jpg'
        		);
			
				if(!empty($iphone_project_backers[$i]['User']['UserAvatar']))
				{
			
						$image_url = Router::url('/', true).$this->ProjectFund->Project->getImageUrl('UserAvatar', $iphone_project_backers[$i]['User']['UserAvatar'], $image_options);
				}
				else
				{
           			 $iphone_project_backers[$i]['User']['UserAvatar']['id'] = constant(sprintf('%s::%s', 'ConstAttachment', 'UserAvatar'));
 
					 $image_url = Router::url('/', true).$this->ProjectFund->Project->getImageUrl('UserAvatar', $iphone_project_backers[$i]['User']['UserAvatar'], $image_options);
				}
				
				if($iphone_project_backers[$i]['Project']['User']['id']==$this->Auth->user('id'))
				{
					$Backers_amount_display=1;
				}
				else
				{
					$Backers_amount_display=0;
				}
				$iphone_project_backer[$i]['Backer_username'] = $iphone_project_backers[$i]['User']['username'];
				$iphone_project_backer[$i]['Backer_user_image'] = $image_url;
				$iphone_project_backer[$i]['Backer_created'] = $created;
				$iphone_project_backer[$i]['Backer_reward'] = $iphone_project_backers[$i]['ProjectReward']['reward'];
				$iphone_project_backer[$i]['Other_projects'] = $other_count;
				$iphone_project_backer[$i]['Backers_amount'] = $iphone_project_backers[$i]['ProjectFund']['amount'];
				$iphone_project_backer[$i]['Backers_amount_dispaly'] = $Backers_amount_display;
			}
			$this->view = 'Json';
			
			$this->set('json',$iphone_project_backer);
		
		}
        $this->set('projectFunds', $this->paginate());
        if (!empty($this->request->params['named']['project_id'])) {
            $project = $this->ProjectFund->Project->find('first', array(
                'conditions' => array(
                    'Project.id = ' => $this->request->params['named']['project_id']
                ) ,
                'recursive' => - 1
            ));
            $this->set('project', $project);
        }
		unset($conditions['ProjectFund.is_given']);
		unset($conditions['ProjectFund.project_reward_id !=']);
		$this->set('all_count', $this->ProjectFund->find('count', array(
            'conditions' => $conditions
        )));
		$conditions['ProjectFund.is_given']=1;
		$this->set('given_count', $this->ProjectFund->find('count', array(
            'conditions' => $conditions
        )));
        $conditions['ProjectFund.is_given']=0;
		$conditions['ProjectFund.project_reward_id !='] = 0;
		$this->set('not_given_count', $this->ProjectFund->find('count', array(
            'conditions' => $conditions
        )));
        $this->set($conditions);
        if (!empty($this->request->params['named']['type']) and $this->request->params['named']['type'] == 'mydonations') {
            $this->autoRender = false;
            $this->render('mydonations');
        }
		if (!empty($this->request->params['named']['type']) and $this->request->params['named']['type'] == 'backers') {
            $this->autoRender = false;
            $this->render('backers');
        }
    }
    public function add($project_id = null)
    {
        if (is_null($project_id) && empty($this->request->data['ProjectFund'])) {
            throw new NotFoundException(__l('Invalid request'));
        }
        $this->ProjectFund->Behaviors->detach('Logable');
        if (!empty($this->request->data['ProjectFund']['project_id'])) {
            $project_id = $this->request->data['ProjectFund']['project_id'];
        }
        $project = $this->ProjectFund->Project->find('first', array(
            'conditions' => array(
                'Project.id' => $project_id,
                'Project.admin_suspend' => 0,
                'Project.is_active' => 1,
                'OR' => array(
                    array(
                        'Project.project_status_id' => ConstProjectStatus::OpenForFunding,
                    ) ,
                    array(
                        'Project.project_status_id' => ConstProjectStatus::GoalReached,
                    ) ,
                    array(
                        'Project.project_status_id' => ConstProjectStatus::ReserveAmountReached,
                    ) ,
                ) ,
            ) ,
            'contain' => array(
                'Attachment',
                'ProjectReward'=>array(
					'order'=>array(
						'ProjectReward.pledge_amount'=>'asc'
					)
				),
                'User'
            ) ,
            'recursive' => 1
        ));
        if (empty($project)) {
            throw new NotFoundException(__l('Invalid request'));
        }
        if ($project['Project']['user_id'] == $this->Auth->user('id') and !Configure::read('Project.is_allow_owner_fund_own_project')) {
            $this->Session->setFlash(__l('You cannot fund your own project') , 'default', null, 'error');
            $this->redirect(array(
                'controller' => 'projects',
                'action' => 'view',
                $project['Project']['slug']
            ));
        }
        $projects_count = $this->ProjectFund->Project->find('count', array(
            'conditions' => array(
                'Project.user_id' => $this->Auth->User('id')
            )
        ));
        if ($projects_count and $project['Project']['user_id'] != $this->Auth->user('id') and !Configure::read('Project.is_allow_owners_to_fund_other_projects')) {
            $this->Session->setFlash(__l('You cannot fund projects') , 'default', null, 'error');
            $this->redirect(array(
                'controller' => 'projects',
                'action' => 'view',
                $project['Project']['slug']
            ));
        }
        if (strtotime(date('Y-m-d 23:59:59', strtotime($project['Project']['project_funding_end_date']))) <= time()) {
            $this->Session->setFlash(__l('Project fund has been closed') , 'default', null, 'error');
            $this->redirect(array(
                'controller' => 'projects',
                'action' => 'view',
                $project['Project']['slug']
            ));
        }
        if (strtotime(date('Y-m-d 23:59:59', strtotime($project['Project']['project_funding_end_date']))) > time() && !(Configure::read('Project.is_allow_over_funding') && $project['Project']['is_allow_over_funding']) && $project['Project']['needed_amount'] <= $project['Project']['collected_amount']) {
            $this->Session->setFlash(__l('Project has been not allowed overfunding') , 'default', null, 'error');
            $this->redirect(array(
                'controller' => 'projects',
                'action' => 'view',
                $project['Project']['slug']
            ));
        }
        $this->pageTitle = $project['Project']['name'] . ' - ' . __l('Pledge');
        if (!empty($this->request->data) && !$_GET['key']) {
            $this->ProjectFund->create();
            if (!empty($this->request->data['ProjectFund']['project_reward_id']) && $this->request->data['ProjectFund']['project_reward_id'] == '-1') {
                unset($this->request->data['ProjectFund']['project_reward_id']);
            }
            $this->ProjectFund->set($this->request->data);
            $this->request->data['ProjectFund']['user_id'] = $this->Auth->user('id');
			$userProfile = $this->ProjectFund->User->UserProfile->find('first', array(
                'conditions' => array(
                    'UserProfile.user_id' => $project['Project']['user_id']
                ) ,
                'fields' => array(
                    'UserProfile.id',
                    'UserProfile.paypal_account'
                ) ,
                'recursive' => -1
            ));
			$this->request->data['ProjectFund']['site_fee'] = round($this->request->data['ProjectFund']['amount']*(Configure::read('Project.fund_commission_percentage') /100) , 2);
			$this->request->data['ProjectFund']['is_delayed_chained_payment'] = 0;
            if ($this->ProjectFund->validates()) {
                $this->ProjectFund->save($this->request->data);
                $this->redirect(array(
                    'controller' => 'payments',
                    'action' => 'order',
                    $this->ProjectFund->id,
                ));
            } else {
                if (!empty($this->ProjectFund->validationErrors['project_reward_id'])) {
                    $this->ProjectFund->validationErrors['project_reward'] = $this->ProjectFund->validationErrors['project_reward_id'];
                    unset($this->ProjectFund->validationErrors['project_reward_id']);
                    unset($this->request->data['ProjectFund']['project_reward']);
                }
				if(($project['Project']['project_status_id'] == ConstProjectStatus::ReserveAmountReached) || ($project['Project']['project_status_id'] == ConstProjectStatus::GoalReached)){
                $this->Session->setFlash(__l('Problem in funding.') , 'default', null, 'error');
                }
                else
                {
                 $this->Session->setFlash(__l('Problem in pledging.') , 'default', null, 'error');
                }
            }
        }
        $this->request->data['ProjectFund']['project_id'] = $project_id;
        if (!empty($this->request->params['named']['project_reward_id'])) {
            $this->request->data['ProjectFund']['project_reward'] = $this->request->params['named']['project_reward_id'];
            $this->request->data['ProjectFund']['project_reward_id'] = $this->request->params['named']['project_reward_id'];
            $project_reward = $this->ProjectFund->ProjectReward->find('first', array(
                'conditions' => array(
                    'ProjectReward.id' => $this->request->params['named']['project_reward_id']
                ) ,
                'fields' => array(
                    'ProjectReward.pledge_amount'
                ) ,
                'recursive' => - 1
            ));
            if (!empty($project_reward)) {
                $this->request->data['ProjectFund']['amount'] = $project_reward['ProjectReward']['pledge_amount'];
            }
        }
        if ($project['Project']['pledge_type_id'] == ConstPledgeTypes::Fixed) {
            $this->request->data['ProjectFund']['amount'] = $project['Project']['min_amount_to_fund'];
        }
        $this->set(compact('project'));
    }
    public function edit_fund()
    {
        if (empty($this->request->params['named']['type']) or empty($this->request->params['named']['project_fund'])) {
            throw new NotFoundException(__l('Invalid request'));
        }
        $this->request->data['ProjectFund']['id'] = $this->request->params['named']['project_fund'];
        if ($this->request->params['named']['type'] == 'cancel') {
            $this->request->data['ProjectFund']['is_cancelled'] = 1;
        }
        $this->loadModel('Payment');
        $projectFund = $this->ProjectFund->find('first', array(
            'conditions' => array(
                'ProjectFund.id' => $this->request->params['named']['project_fund']
            ) ,
            'contain' => array(
                'Project',
                'User'
            ) ,
            'recursive' => 0
        ));
        $buyer = $this->ProjectFund->User->find('first', array(
            'conditions' => array(
                'User.id' => $projectFund['Project']['user_id']
            ) ,
            'fields' => array(
                'User.id',
                'User.username',
                'User.email'
            ) ,
            'recursive' => - 1
        ));
        if ($projectFund['ProjectFund']['is_cancelled'] || $projectFund['ProjectFund']['is_refunded']) {
            throw new NotFoundException(__l('Invalid request'));
        }
        if (!(!empty($projectFund) and (((($projectFund['ProjectFund']['user_id'] == $this->Auth->user('id') and (Configure::read('Project.is_allow_pledge_cancel_by_backer'))) or ($projectFund['Project']['user_id'] == $this->Auth->user('id') and (Configure::read('Project.is_allow_pledge_cancel_by_owner')))) and (strtotime('+' . Configure::read('Project.minimum_days_before_pledge_cancel') . ' days') < strtotime($projectFund['Project']['project_funding_end_date']))) or $this->Auth->user('user_type_id') == ConstUserTypes::Admin) and ($projectFund['Project']['project_status_id'] == ConstProjectStatus::OpenForFunding || $projectFund['Project']['project_status_id'] == ConstProjectStatus::ReserveAmountReached || $projectFund['Project']['project_status_id'] == ConstProjectStatus::GoalReached))) {
            throw new NotFoundException(__l('Invalid request'));
        }
        $this->ProjectFund->Behaviors->detach('Logable');
        $this->request->data['ProjectFund']['project_id'] = $projectFund['ProjectFund']['project_id'];
        $this->request->data['ProjectFund']['user_id'] = $projectFund['ProjectFund']['user_id'];
        $return = $this->Payment->refundProjectFund($this->request->data['ProjectFund']['id']);
        if (empty($return['error'])) {
            $this->ProjectFund->save($this->request->data, false);
            // Project fund cancelled notify Mail (process owner or backer)
            if ($projectFund['Project']['user_id'] == $this->Auth->user('id')) {
                $this->ProjectFund->_sendAlertOnProjectStatus($projectFund, 'Project Fund Cancelled By Owner', $buyer);
                $this->ProjectFund->_sendAlertOnProjectStatus($projectFund, 'Project Fund Cancelled By Owner Admin', '', 'admin');
            } else {
                $this->ProjectFund->_sendAlertOnProjectStatus($projectFund, 'Project Fund Cancelled By Backer', $buyer, 'buyer');
                $this->ProjectFund->_sendAlertOnProjectStatus($projectFund, 'Project Fund Cancelled By Backer Admin', '', 'admin');
            }
            $this->Session->setFlash(__l('Project Fund has been cancelled') , 'default', null, 'success');
        } else {
            $this->Session->setFlash(__l('Project Fund could not be cancelled. Please, try again.') , 'default', null, 'error');
        }
        if (!empty($this->request->params['named']['return_page'])) {
            if ($this->request->params['named']['return_page'] == 'admin') {
                $this->redirect(array(
                    'controller' => 'project_funds',
                    'action' => 'index',
                    'admin' => true,
                ));
            } else {
                $this->redirect(array(
                    'controller' => 'users',
                    'action' => 'dashboard',
                ));
            }
        } else {
            $this->redirect(array(
                'controller' => 'projects',
                'action' => 'view',
                $projectFund['Project']['slug']
            ));
        }
    }
    public function admin_index()
    {
        $this->_redirectGET2Named(array(
            'q'
        ));
        $this->pageTitle = __l('Project Funds');
        $this->ProjectFund->recursive = 0;
        $conditions = array();
        if (!empty($this->request->params['named']['type'])) {
            if ($this->request->params['named']['type'] == 'backed') {
                $conditions['ProjectFund.is_paid'] = 0;
                $conditions['ProjectFund.is_refunded'] = 0;
                $conditions['ProjectFund.is_cancelled'] = 0;
                $this->pageTitle.= __l(' - Backed ');
            }
            elseif ($this->request->params['named']['type'] == 'captured') {
                $conditions['ProjectFund.is_paid'] = 1;
                $conditions['Project.project_status_id <>'] = ConstProjectStatus::OpenForFunding;
                $conditions['ProjectFund.is_refunded'] = 0;
                $conditions['ProjectFund.is_cancelled'] = 0;
                $this->pageTitle.= __l(' - Captured ');
            }
            elseif ($this->request->params['named']['type'] == 'authorized') {
                $conditions['ProjectFund.is_paid'] = 0;
                $conditions['Project.project_status_id'] = ConstProjectStatus::OpenForFunding;
                $conditions['ProjectFund.is_refunded'] = 0;
                $conditions['ProjectFund.is_cancelled'] = 0;
                $conditions['ProjectFund.is_failed <>'] = 1;
                $this->pageTitle.= __l(' - Authorized ');
            }
            elseif ($this->request->params['named']['type'] == 'failed') {
                $conditions['ProjectFund.is_paid'] = 0;
                $conditions['ProjectFund.is_refunded'] = 0;
                $conditions['ProjectFund.is_cancelled'] = 0;
                $conditions['ProjectFund.is_failed'] = 1;
                $this->pageTitle.= __l(' - Failed ');
            }
            elseif ($this->request->params['named']['type'] == 'voided') {
                $conditions['ProjectFund.is_cancelled'] = 1;
                $this->pageTitle.= __l(' - Voided ');
            }

             elseif ($this->request->params['named']['type'] == 'refunded') {
                $conditions['ProjectFund.is_refunded'] = 1;
                $this->pageTitle.= __l(' - Refunded ');
            } elseif ($this->request->params['named']['type'] == 'paid') {
                $conditions['ProjectFund.is_paid'] = 1;
                $this->pageTitle.= __l(' - Paid ');
            } elseif ($this->request->params['named']['type'] == 'cleared') {
                $conditions['ProjectFund.is_paid'] = 1;
                $this->pageTitle.= __l(' - Cleared');
            } else if ($this->request->params['named']['type'] == 'pipeline') {
                $conditions['ProjectFund.is_paid'] = 0;
                $conditions['ProjectFund.is_refunded'] = 0;
                $conditions['ProjectFund.is_cancelled'] = 0;
                $this->pageTitle.= __l(' - Pipeline');
            } elseif ($this->request->params['named']['type'] == 'lost') {
                $conditions['ProjectFund.is_refunded'] = 1;
                $this->pageTitle.= __l(' - Lost');
            }
        } else {
            $conditions['OR'][]['ProjectFund.is_paid'] = 0;
            $conditions['OR'][]['ProjectFund.is_paid'] = 1;
        }
        if (!empty($this->request->params['named']['stat']) && $this->request->params['named']['stat'] == 'day') {
            $conditions['TO_DAYS(NOW()) - TO_DAYS(ProjectFund.created) <= '] = 0;
            $this->pageTitle.= __l(' - Added today');
        }
        if (!empty($this->request->params['named']['stat']) && $this->request->params['named']['stat'] == 'week') {
            $conditions['TO_DAYS(NOW()) - TO_DAYS(ProjectFund.created) <= '] = 7;
            $this->pageTitle.= __l(' - Added in this week');
        }
        if (!empty($this->request->params['named']['stat']) && $this->request->params['named']['stat'] == 'month') {
            $conditions['TO_DAYS(NOW()) - TO_DAYS(ProjectFund.created) <= '] = 30;
            $this->pageTitle.= __l(' - Added in this month');
        }
        if (!empty($this->request->params['named']['project'])) {
            $conditions['ProjectFund.project_id'] = $this->request->params['named']['project'];
            $project_name = $this->ProjectFund->Project->find('first', array(
                'conditions' => array(
                    'Project.id' => $this->request->params['named']['project'],
                ) ,
                'fields' => array(
                    'Project.name',
                ) ,
                'recursive' => - 1,
            ));
            $this->pageTitle.= sprintf(__l(' - %s') , $project_name['Project']['name']);
        }
        if (!empty($this->request->params['named']['project_id'])) {
            $conditions['ProjectFund.project_id'] = $this->request->params['named']['project_id'];
            $project_name = $this->ProjectFund->Project->find('first', array(
                'conditions' => array(
                    'Project.id' => $this->request->params['named']['project_id'],
                ) ,
                'fields' => array(
                    'Project.name',
                ) ,
                'recursive' => - 1,
            ));
            $this->pageTitle.= sprintf(__l(' - %s') , $project_name['Project']['name']);
        } elseif (!empty($this->request->params['named']['user_id'])) {
            $conditions['ProjectFund.user_id'] = $this->request->params['named']['user_id'];
            $user = $this->{$this->modelClass}->User->find('first', array(
                'conditions' => array(
                    'User.id' => $this->request->params['named']['user_id']
                ) ,
                'fields' => array(
                    'User.id',
                    'User.username'
                ) ,
                'recursive' => - 1
            ));
            if (empty($user)) {
                throw new NotFoundException(__l('Invalid request'));
            }
            $this->pageTitle.= sprintf(__l(' - %s') , $user['User']['username']);
        }
        if (!empty($this->request->params['named']['q'])) {
            $conditions['AND']['OR'][]['Project.name LIKE'] = '%' . $this->request->params['named']['q'] . '%';
            $conditions['AND']['OR'][]['Project.description LIKE'] = '%' . $this->request->params['named']['q'] . '%';
            $conditions['AND']['OR'][]['Project.short_description LIKE'] = '%' . $this->request->params['named']['q'] . '%';
            $this->pageTitle.= sprintf(__l(' - Search - %s') , $this->request->params['named']['q']);
			$this->request->data['ProjectFund']['q'] = $this->request->params['named']['q'];
        }
        if (isset($this->request->params['named']['user_paypal_connection_id']) && !empty($this->request->params['named']['user_paypal_connection_id'])) {
            $conditions['ProjectFund.user_paypal_connection_id'] = $this->request->params['named']['user_paypal_connection_id'];
            $this->pageTitle.= __l(' -  By PayPal Connection');
        }
        $this->set('authorized_count', $this->ProjectFund->find('count', array(
                'conditions' => array(
                    'Project.project_status_id' => ConstProjectStatus::OpenForFunding,
                    'ProjectFund.is_paid' => 0,
                    'ProjectFund.is_refunded' => 0,
                    'ProjectFund.is_cancelled' => 0,
                    'ProjectFund.is_failed <>' => 1,
                )
            )));
            $this->set('failed_count', $this->ProjectFund->find('count', array(
                'conditions' => array(
                    'ProjectFund.is_paid' => 0,
                    'ProjectFund.is_refunded' => 0,
                    'ProjectFund.is_cancelled' => 0,
                    'ProjectFund.is_failed' => 1
                )
            )));
            $this->set('captured_count', $this->ProjectFund->find('count', array(
                'conditions' => array(
                    'Project.project_status_id <>' => ConstProjectStatus::OpenForFunding,
                    'ProjectFund.is_paid' => 1,
                    'ProjectFund.is_refunded' => 0,
                    'ProjectFund.is_cancelled' => 0
                )
            )));
            $this->set('voided_count', $this->ProjectFund->find('count', array(
                'conditions' => array(
                    'ProjectFund.is_cancelled' => 1
                )
            )));


            
        $this->set('backed_count', $this->ProjectFund->find('count', array(
            'conditions' => array(
                'ProjectFund.is_paid = ' => 0,
                'ProjectFund.is_refunded = ' => 0,
                'ProjectFund.is_cancelled = ' => 0,
            )
        )));
        $this->set('refunded_count', $this->ProjectFund->find('count', array(
            'conditions' => array(
                'ProjectFund.is_refunded = ' => 1,
            )
        )));
        $this->set('paid_count', $this->ProjectFund->find('count', array(
            'conditions' => array(
                'ProjectFund.is_paid = ' => 1,
            )
        )));
        $this->paginate = array(
            'conditions' => $conditions,
            'contain' => array(
                'Project' => array(
                    'ProjectStatus',
                ) ,
                'ProjectReward',
                'User',
            ) ,
            'order' => array(
                'ProjectFund.id' => 'desc'
            )
        );
        $this->set('projectFunds', $this->paginate());
        $total_pledge_conditions['ProjectFund.is_paid'] = 0;
        $total_pledge_conditions['ProjectFund.is_refunded'] = 0;
        $total_pledge_conditions['ProjectFund.is_cancelled'] = 0;
        $pledge = $this->ProjectFund->find('first', array(
            'conditions' => $total_pledge_conditions,
            'fields' => array(
                'SUM(ProjectFund.amount) as total_amount',
            ) ,
            'recursive' => - 1
        ));
        $total_pledge = ($pledge[0]['total_amount']) ? $pledge[0]['total_amount'] : 0;
        $total_paid_conditions['ProjectFund.is_paid'] = 1;
        $total_paid_conditions['ProjectFund.is_refunded'] = 0;
        $total_paid_conditions['ProjectFund.is_cancelled'] = 0;
        $paid = $this->ProjectFund->find('first', array(
            'conditions' => $total_paid_conditions,
            'fields' => array(
                'SUM(ProjectFund.amount) as total_amount',
            ) ,
            'recursive' => - 1
        ));
        $total_paid = ($paid[0]['total_amount']) ? $paid[0]['total_amount'] : 0;
        $total_refunded_conditions['ProjectFund.is_refunded'] = 1;
        $refunded = $this->ProjectFund->find('first', array(
            'conditions' => $total_refunded_conditions,
            'fields' => array(
                'SUM(ProjectFund.amount) as total_amount',
            ) ,
            'recursive' => - 1
        ));
        $total_refunded = ($refunded[0]['total_amount']) ? $refunded[0]['total_amount'] : 0;
        $this->set(compact('projectStatuses'));
        $this->set('total_pledge', $total_pledge);
        $this->set('total_paid', $total_paid);
        $this->set('total_refunded', $total_refunded);
    }
    public function admin_delete($id = null)
    {
        if (is_null($id)) {
            throw new NotFoundException(__l('Invalid request'));
        }
        if ($this->ProjectFund->delete($id)) {
            $this->Session->setFlash(__l('Project Fund deleted') , 'default', null, 'success');
            $this->redirect(array(
                'action' => 'index'
            ));
        } else {
            throw new NotFoundException(__l('Invalid request'));
        }
    }
    public function view($id = null)
    {
        $this->pageTitle = __l('Reward Voucher');
        if (is_null($id)) {
            throw new NotFoundException(__l('Invalid request'));
        }
        $conditions['ProjectFund.id'] = $id;
        $conditions['OR'][]['ProjectFund.is_paid'] = 0;
        $conditions['OR'][]['ProjectFund.is_paid'] = 1;
        $conditions['ProjectFund.is_refunded'] = 0;
        $conditions['ProjectFund.is_cancelled'] = 0;
        $projectFund = $this->ProjectFund->find('first', array(
            'conditions' => $conditions,
            'contain' => array(
                'Project' => array(
                    'User'
                ) ,
                'User',
                'ProjectReward',
            ) ,
            'recursive' => 2
        ));
        if (empty($projectFund) || ($projectFund['Project']['User']['id'] != $this->Auth->user('id') && $projectFund['ProjectFund']['user_id'] != $this->Auth->user('id') && $this->Auth->user('user_type_id') != ConstUserTypes::Admin)) {
            throw new NotFoundException(__l('Invalid request'));
        }
        if (empty($projectFund['ProjectFund']['project_reward_id'])) {
            $this->Session->setFlash(__l('No rewards selected') , 'default', null, 'success');
            $this->redirect(array(
                'controller' => 'projects',
                'action' => 'view',
                $projectFund['Project']['slug']
            ));
        }
        $this->set('projectFund', $projectFund);
        if (!empty($this->request->params['named']['type']) && $this->request->params['named']['type'] == 'print') {
            $this->layout = 'print';
        }
    }
    public function test()
    {
        $projectFunds = $this->ProjectFund->find('all', array(
            'recursive' => - 1,
            'fields' => array(
                'sum(ProjectFund.site_fee) as fee',
                'ProjectFund.project_id'
            ) ,
            'group' => 'ProjectFund.project_id',
        ));
        foreach($projectFunds as $projectFund) {
            $data = array();
            if ($projectFund['0']['fee']) {
                $data['Project']['commission_amount'] = $projectFund['0']['fee'];
                $data['Project']['id'] = $projectFund['ProjectFund']['project_id'];
                $this->ProjectFund->Project->Behaviors->detach('Logable');
                $this->ProjectFund->Project->save($data);
            }
        }
        exit;
    }
    public function check_qr()
    {
        if (!empty($this->request->data)) {
            $coupon_code = $this->request->data['ProjectFund']['coupon_code'];
            $unique_coupon_code = $this->request->data['ProjectFund']['unique_coupon_code'];
        } else {
            $fund_id = $this->request->params['pass'][0];
            $projectFund_detail = $this->ProjectFund->find('first', array(
            'conditions' => array('ProjectFund.id'=>$fund_id),
            'contain' => array(
                'Project',
				'User',
            ) ,
            'recursive' => 1
        ));
            $coupon_code = $projectFund_detail['ProjectFund']['coupon_code'];
            $unique_coupon_code = $this->request->params['pass'][1];
        }
        if (is_null($coupon_code) || is_null($unique_coupon_code)) {
            throw new NotFoundException(__l('Invalid request'));
        }
        $this->pageTitle = __l('Voucher');
        $conditions['ProjectFund.coupon_code'] = $coupon_code;
        $conditions['ProjectFund.unique_coupon_code'] = $unique_coupon_code;
        $projectFund = $this->ProjectFund->find('first', array(
            'conditions' => $conditions,
            'contain' => array(
                'Project',
				'User',
            ) ,
            'recursive' => 1
        ));
        if (empty($projectFund)) {
            $this->Session->setFlash(__l('Invalid voucher code') , 'default', null, 'error');
            $this->redirect(Router::url('/', true));
        }
        if ((($this->Auth->user('user_type_id') == ConstUserTypes::User) && ($this->Auth->user('id') != $projectFund['ProjectFund']['user_id'] || $this->Auth->user('id') != $projectFund['Project']['user_id']))) {
           //$this->Session->setFlash(__l('You don\'t have rights to view this page') , 'default', null, 'error');
        //   $this->redirect(Router::url('/', true));
        }
        if ($projectFund['ProjectFund']['is_given'] == 1) {
            $this->Session->setFlash(__l('This voucher used already') , 'default', null, 'error');
        }
        if (!empty($this->request->data)) {
	        $this->ProjectFund->Behaviors->detach('Logable');
            $project_fund_data['ProjectFund']['is_given'] = 1;
            $project_fund_data['ProjectFund']['id'] =  $projectFund['ProjectFund']['id'];
	        $project_fund_data['ProjectFund']['user_id'] = $projectFund['ProjectFund']['user_id'];
	        $project_fund_data['ProjectFund']['project_id'] = $projectFund['ProjectFund']['project_id'];
	        $project_fund_data['ProjectFund']['reward_given_date'] = date('Y-m-d H:i:s');
            if ($this->ProjectFund->save($project_fund_data)) {
                $projectFund['ProjectFund']['is_given'] = 1;
                $this->Session->setFlash(__l('Coupon used successfully') , 'default', null, 'success');
            }
        }
		$this->request->data['ProjectFund']['id'] = $projectFund['ProjectFund']['id'];
        $this->request->data['ProjectFund']['coupon_code'] = $coupon_code;
        $this->request->data['ProjectFund']['unique_coupon_code'] = $unique_coupon_code;
        $this->set('projectFund', $projectFund);
    }
}
?>